<script>
	// 引入vue3 getCurrentInstance 
	import {
		getCurrentInstance
	} from 'vue'
	import pinia from '@/store/index'
	import {
		useMsgStore
	} from '@/store/message';
	import {
		useloginStore
	} from '@/store/login';
	
	import { useAppStore } from './store/app'
	
	import { useThemeStore } from './store/theme'

	const getTheme = useThemeStore(pinia)

	const msgStore = useMsgStore(pinia)

	const userStore = useloginStore(pinia)
	
	const appStore = useAppStore()
	
	export default {

		onLaunch: function() {


			appStore.getConfig()
			
			getTheme.getTheme()

			// 初始化APP设置
			let setting = uni.getStorageSync('appSetting') ?? '';

			if (!setting) {
				userStore.setAppSetting({
					voiceStatus: true,
					vibrateStatus: false,
					circleAvatar: false
				});
			} else {
				userStore.setAppSetting(setting);
			}

			// 获取全局配置
			userStore.getGlobalConfig();

			uni.getSystemInfo({

				success: function(e) {

					console.log()
					uni.setStorageSync('osName', e.osName)

					let paddingB = 0;
					// 获取 appContext  上下文
					const {
						appContext
					} = getCurrentInstance();
					appContext.config.globalProperties.StatusBar = e.statusBarHeight;
					// #ifndef MP
					if (e.platform == 'android') {
						appContext.config.globalProperties.CustomBar = e.statusBarHeight + 50;
					} else {
						appContext.config.globalProperties.CustomBar = e.statusBarHeight + 45;
					};
					uni.setStorageSync('TopHeight', appContext.config.globalProperties.CustomBar)
					// #endif
					// #ifdef MP-WEIXIN
					let custom = wx.getMenuButtonBoundingClientRect();
					appContext.config.globalProperties.Custom = custom;
					appContext.config.globalProperties.CustomBar = custom.bottom + custom.top - e
						.statusBarHeight;
					uni.setStorageSync('TopHeight', appContext.config.globalProperties.CustomBar)
					// #endif     

					// #ifdef MP-ALIPAY
					appContext.config.globalProperties.CustomBar = e.statusBarHeight + e.titleBarHeight;
					uni.setStorageSync('TopHeight', appContext.config.globalProperties.CustomBar)
					// #endif

					// #ifdef MP
					try {

						var res = uni.getSystemInfoSync();
						res.model = res.model.replace(' ', '');
						res.model = res.model.toLowerCase();
						var res1 = res.model.indexOf('iphonex');
						if (res1 > 5) {
							res1 = -1;
						}
						var res2 = res.model.indexOf('iphone1');
						if (res2 > 5) {
							res2 = -1;
						}
						if (res1 != -1 || res2 != -1) {
							paddingB = uni.upx2px(50);
						}

						uni.setStorageSync('screenHeight', res.windowWidth)


					} catch (e) {
						return null;
					}
					// #endif
					// #ifdef H5
					paddingB = uni.upx2px(100);
					// #endif
					// 获取设备底部高度
					appContext.config.globalProperties.inlineTools = paddingB;
					// 设置全局底部导航栏高度
					appContext.config.globalProperties.navBarHeight = uni.upx2px(100);

					uni.setStorageSync('screenHeight', e.windowWidth)

				}
			})

			uni.getPushClientId({
				success: (res) => {
					console.log('初始化cid：', res.cid)
					uni.setStorageSync('cid', res.cid)
				},
				fail(err) {
					console.log(err)
				}
			})
			// 只有app才有推送权限
			// #ifdef APP
			uni.onPushMessage((res) => {
				console.log("收到推送消息：", res)
				let data = res.data;
				if (res.type == 'click') {
					let playload = data.payload;
					let toUser = playload.toContactId ? playload.toContactId : '';
					// 如果是音视频通话则不

					if (playload.type == 'webrtc') {
						return;
					}

					uni.navigateTo({
						url: "/pages/message/chat?id=" + toUser
					})

				} else if (res.type == 'receive') {

					let appStatus = this.appStatus;
					console.log("app状态：", appStatus)
					// 如果app在后台运行,创建通知栏
					if (!appStatus) {
						console.log("创建通知栏")
						let message = {
							title: data.title,
							content: data.content,
							payload: data.payload,

						}
						let systemInfo = uni.getSystemInfoSync();
						// 判断平台,如果是安卓就去下载头像并展示头像
						if (systemInfo.platform === 'android') {
							uni.downloadFile({
								url: data.payload.fromUser.avatar,
								success: (res) => {
									if (res.statusCode === 200) {
										message.icon = res.tempFilePath
										uni.createPushMessage(message)
									}
								}
							});
						} else if (systemInfo.platform === 'ios') {
							uni.createPushMessage(message)
						}
					}
				}
			})
			// #endif
		},
		onUnload() {
			this.scoketClose()
			this.socketIo.traderDetailIndex = 100 // 初始化 tabIndex 
			console.log('onUnload');
		},

		onShow: function() {
			if (!this.socketIo.checkStatus()) {
				console.log('ws断线了，重新链接！');
				uni.$emit('socketStatus', false);
				this.getWebsocketData();
			}
			this.appStatus = true;
			console.log('App Show')
			
			
			
		},
		methods: {

			scoketClose() {
				this.socketIo.connectNum = 1
				const data = {
					type: "close"
				};
				this.socketIo.send(data); // 这是给后端发送特定数据 关闭推送
				this.socketIo.Close(); // 主动 关闭连接 ， 不会重连
			},
			getWebsocketData() {
				// 获取用户信息
				var userInfo = uni.getStorageSync('userInfo');
				var _this = this;
				// 要发送的数据包
				const data = {
					type: "ping"
				};
				// 打开连接
				this.socketIo.connectSocketInit(data);
				uni.$off("getPositonsOrder");
				// 接收数据,全局监听
				uni.$on("getPositonsOrder", (res) => {
					//console.log(res)
					var userInfo = uni.getStorageSync('userInfo');
					
					let data = res.data;
					
					this.connect = true;

					switch (res['type']) {
						// 服务端ping客户端
						case 'ping':
							this.socketIo.send({
								type: "pong"
							});
							break;
						case 'pong':
							userStore.$patch({
								multiport: res.multiport
							})
							break;
							// 登录 更新用户列表
						case 'init':
							// 设置全局clientId
							uni.setStorageSync('client_id', res.client_id);

							if (userInfo) {
								this.$api.LoginApi.bindUid({
									client_id: res['client_id'],
									user_id: userInfo.user_id,
									cid: uni.getStorageSync('cid')
								}).then(e => {
									this.socketIo.send({
										type: "bindUid",
										user_id: userInfo.user_id,
										token: uni.getStorageSync("token")
									});
								}).catch(error => {})
							}

							break;
							//上线、下线通知
						case "isOnline":
							msgStore.updateContacts({
								id: data.id,
								is_online: data.is_online
							});
							break;
						case "offline":
							let clientId = uni.getStorageSync('client_id');
							if (data.id == userInfo.user_id && data.client_id != clientId && data.isMobile) {
								uni.showToast({
									title: "您的账号在其他地方登录，已被迫下线！",
									icon: "none",
									duration: 2500
								})
								userStore.logout();
							}
							break;
						case 'simple':
						case 'group':
							// 只要不是自己发的,才可以播放声音
							if (data.fromUser.id != userInfo.user_id) {
								const contact = msgStore.getContact(data.toContactId);
								// 如果开启了声音才播放
								if (data.toContactId == 'system' || contact.is_notice == 1) {
									this.playSound();
								}
							}
							this.appendMessage(res);
							break;
						case "setChatTop":
							msgStore.updateContacts({
								id: data.id,
								is_top: data.is_top
							});
							break;
						case "setIsNotice":
							msgStore.updateContacts({
								id: data.id,
								is_notice: data.is_notice
							});
							break;
							// 新增加了群聊
						case "addGroup":
							msgStore.appendContacts(data);
							this.$api.LoginApi.bindGroup({
								client_id: uni.getStorageSync('client_id'),
								group_id: data.id
							});
							break;
							// 设置群管理员
						case "setManager":
						case "addGroupUser":
						case "removeUser":
							msgStore.updateContacts({
								id: data.group_id,
								avatar: data.avatar
							});
							uni.$emit('updateGroup', res);
							break;
							// 修改群组名称
						case "editGroupName":
							msgStore.updateContacts({
								id: data.id,
								displayName: data.displayName
							});
							break;
						case "removeGroup":
							msgStore.deleteContacts({
								id: data.group_id
							})
							break;
							// 发布公告
						case "setNotice":
							msgStore.updateContact({
								id: data.group_id,
								notice: data.notice
							});
							break;
							// 群聊设置
						case "groupSetting":
							msgStore.updateContact({
								id: data.group_id,
								setting: data.setting
							});
							break;
						case "appendContact":
							console.log(123123, data);
							msgStore.appendContacts(data);
							break;
						case 'webrtc':
							let platform = 'h5';
							//#ifdef H5
							platform = 'h5';
							//#endif
							//#ifdef APP-PLUS
							platform = 'app';
							//#endif
							if (data.fromUser.id == userInfo.user_id) {
								// 挂断的情况下解锁webrtc
								if ([902, 903, 905, 906, 907].includes(parseInt(data.extends.code))) {
									msgStore.webrtcLock = false;
								}
								// 如果是当前设备发出的消息则不处理
								if (data.extends.isMobile == 1 || data.extends.event == 'calling') {
									if (data.extends.event == 'calling') {
										this.appendMessage(res);
									}
									return;
								}

							}
							// 如果是多端在线,要将在通话中的用户锁定
							if (data.extends.event == 'offer' || data.extends.event == 'answer') {
								msgStore.webrtcLock = true;
							} else if (data.extends.event == 'hangup') {
								msgStore.webrtcLock = false;
							}
							if (data.extends.event == 'calling') {
								this.appendMessage(res);
								const allroutes = getCurrentPages();
								const cureentRoute = allroutes[allroutes.length - 1].route;
								// 如果当前已经在通话中,通知对方忙线中
								if (cureentRoute == 'pages/message/call') {
									this.$api.msgApi.sendToMsg({
										toContactId: data.fromUser.user_id,
										type: data.extends.type,
										event: 'busy',
										status: data.extends.status,
										code: 907,
										id: data.id,
										msg_id: data.msg_id,
									})
								} else {
									// 小程序不支持音视频聊天
									//#ifdef APP-PLUS || H5
									uni.navigateTo({
										url: '/pages/message/call?msg_id=' + data.id + '&type=' + data
											.extends.type + '&status=' + data.extends.status + '&id=' +
											data.fromUser.user_id + '&name=' + data.fromUser.realname +
											'&avatar=' + encodeURI(data.fromUser.avatar)
									})
									//#endif
								}


							} else {
								uni.$emit('webrtcConn', data);
							}
							break;
						default:
							break;
					}
				})
				// 错误时做些什么
				uni.$on("connectError", () => {
					this.connect = false
					this.scoketError = true
					uni.$emit('socketStatus', false);
				})
			},

			appendMessage(res) {
				let data = res.data;
				if (data.toContactId == 'system') {
					// 系统消息只需要把未读数增加一
					msgStore.$patch({
						sysUnread: msgStore.sysUnread += 1,
					})
				} else {
					let contacts = msgStore.contacts;
					let toUser = data.toContactId;
					// 判断是否是自己,自己发的看接收人是谁，去更新接受人的信息
					var userInfo = uni.getStorageSync('userInfo');
					let addUnread = 1;
					// 自己发送的不需要加
					if (data.fromUser.id == userInfo.user_id) {
						addUnread = 0;
					}
					if (data.toContactId == userInfo.user_id) {
						toUser = data.toUser
					}
					let contact = this.$util.findArray(contacts, toUser);
					if (contact) {
						contact.lastContent = data.content;
						contact.lastSendTime = data.sendTime * 1000;
						contact.type = data.type;
						contact.unread += addUnread;
						// 更新联系人信息
						msgStore.updateContacts(contact);
					} else {
						let newContact = {
							id: data.toContactId,
							displayName: data.fromUser.displayName,
							avatar: data.fromUser.avatar,
							lastContent: data.content,
							lastSendTime: data.sendTime * 1000,
							is_group: data.is_group,
							unread: addUnread,
							is_top: 0,
							dep_id: 0
						}
						contacts.push(newContact);
						msgStore.initContacts(contacts);
					}
					msgStore.catchSocketAction(res);
				}
			},
			playSound() {
				let setting = uni.getStorageSync('appSetting') ?? '';
				if (setting.voiceStatus) {
					let _this = this
					// _this.playing = true
					const innerAudioContext = uni.createInnerAudioContext();
					innerAudioContext.autoplay = true;
					innerAudioContext.src = 'https://file.lcoce.com/static/v5/voice/notice.wav';
					innerAudioContext.onError((res) => {
						//如果音频没有正常播放
					})
					innerAudioContext.onStop((res) => {
						// _this.playing=false
						_this.$forceUpdate()
					})
				}
				if (setting.vibrateStatus) {
					uni.vibrateLong({
						success: function() {
							console.log('手机震动');
						}
					});
				}

			}
		},
		onHide: function() {
			this.appStatus = false;
			// console.log('App Hide')

			// uni.setStorageSync('lang','')

		}
	}
</script>

<style>
	/*每个页面公共css */
	uni-page-body,
	html,
	body,
	page {
		background: #f5f5f7
	}
</style>

<style lang="scss">
	/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
	@import "@/uni_modules/uview-plus/index.scss";

	//@import url("static/css/iconfont.css");
	// 多语言取消屏蔽下方
	// @import url("static/css/stylesheet.css");
	@import url("@/static/css/fonts.scss");
	@import url("static/css/main.css");
	@import url("static/css/icon.css");
	@import url("static/css/reset.css");

	.n-font {
		font-family: "SemiBold";
	}


	.uni-flex {
		width: 100%;
	}
	
	/* start--iPhoneX底部安全区定义--start */
	// .safe-area-inset-bottom {
	//   padding-bottom: 0;  
	//   padding-bottom: constant(safe-area-inset-bottom);  
	//   padding-bottom: env(safe-area-inset-bottom);  
	// } 
	/* end-iPhoneX底部安全区定义--end */
	
</style>